package cn.fcj.f20240328.fsocket;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
/**
 * @项目名称:FSocket
 * @功能描述:读取数据
 * @开发　者:mochhk
 * @邮　　箱:mochhk@163.com
 * @CreateDate:2024/3/29 20:31
 */
public class ReadDataEntity {
    public  static char SPLIT = '\n';
    public static final int BUFFER_LENGTH=120;//缓存大小
    public static final int HEAD_LENGTH=4;//消息头的长度，用来存放body的长度
    public int bodyLen = -1;//数据总长度
    public int currLen = 0;//已读数据长度
    public byte[] byteBody=new byte[0];//包数据
    public String body="";//转成字串数据
    public boolean isFinished=false;//是否成功读取一个包的数据

    /**
     * 添加byte数组到body中
     * @param newByte
     */
    public void addByteToByteBody(byte[] newByte){
        System.arraycopy(newByte, 0, byteBody, currLen, newByte.length);
    }
    public String bodyToString(){
        body= new String(byteBody, StandardCharsets.UTF_8);
        return body;
    }

    /**
     * int到byte[]
     *
     * @param
     * @return
     */
    public static byte[] intToBytes(int value) {
        byte[] result = new byte[4];
        // 由高位到低位
        result[0] = (byte) ((value >> 24) & 0xFF);
        result[1] = (byte) ((value >> 16) & 0xFF);
        result[2] = (byte) ((value >> 8) & 0xFF);
        result[3] = (byte) (value & 0xFF);
        return result;
    }
    /**
     * byte[]转int
     *
     * @param bytes
     * @return
     */
    public static int byteArrayToInt(byte[] bytes) {
        int value = 0;
        // 由高位到低位
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (bytes[i] & 0x000000FF) << shift;// 往高位游
        }
        return value;
    }

    /**
     * 拼接两个数组
     * @param bt1
     * @param bt2
     * @return
     */
    public static byte[] byteMerger(byte[] bt1, byte[] bt2){
        byte[] bt3 = new byte[bt1.length+bt2.length];
        System.arraycopy(bt1, 0, bt3, 0, bt1.length);
        System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
        return bt3;
    }

    /**
     * 读取channel中的数据
     * @param channel
     * @param byteBuffer
     * @return
     * @throws IOException
     */
    public static int readBuffer(SocketChannel channel, ByteBuffer byteBuffer)throws IOException {
        int len=channel.read(byteBuffer);
        if(len==-1){
            System.out.println("channelReadable========断开连接==ip=:"+channel.getRemoteAddress().toString());
            throw new IOException("断开连接");
        }
        return len;
    }

    /**
     * 取出连接中的ip地址
     * @param channel
     * @return
     * @throws IOException
     */
    public static String getChannelIP(SocketChannel channel)throws IOException{
        String ip=channel.getRemoteAddress().toString();
        ip=ip.split(":")[0];
        return ip;
    }
}
